﻿using Domain.QualityInspection_Modelling;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.QualityInspection_ModCom;
using Microsoft.EntityFrameworkCore;
using ReturnValue;

namespace MES.Server.API.Application.Handler.QualityInspection_ModHandler
{
    public class GetQualityInspectionsHandler : IRequestHandler<GetQualityInspectionsCommand, ApiPaging<QualityInspection>>
    {
        private readonly IRepository<QualityInspection> _qualityRepo;

        public GetQualityInspectionsHandler(IRepository<QualityInspection> qualityRepo)
        {
            _qualityRepo = qualityRepo;
        }

        public async Task<ApiPaging<QualityInspection>> Handle(GetQualityInspectionsCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<QualityInspection>
            {
                Code = StatusCode.Success,
                Message = "查询成功"
            };

            // 构建查询
            var query = _qualityRepo.GetAll().AsQueryable();

            // 条件过滤
            if (request.Id.HasValue)
                query = query.Where(q => q.Id == request.Id.Value);

            if (request.ProductionOrderId.HasValue)
                query = query.Where(q => q.ProductionOrderId == request.ProductionOrderId.Value);

            if (request.MaterialGroupId.HasValue)
                query = query.Where(q => q.MaterialGroupId == request.MaterialGroupId.Value);

            // 分页处理
            result.Totalcount = await query.CountAsync(cancellationToken);
            result.TotalPage = await query
                .OrderByDescending(q => q.InspectionTime)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToListAsync(cancellationToken);

            return result;
        }
    }

}
